package com.dongdong.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

@Configuration
public class SchedulerConfig {

    @Autowired
    private DruidDataSource dataSource;
    @Bean
    public Scheduler scheduler(){
        Scheduler scheduler = schedulerFactoryBean().getObject();
        return scheduler;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setSchedulerName("cluster_scheduler");
        bean.setDataSource(dataSource);
        bean.setApplicationContextSchedulerContextKey("application");
        bean.setQuartzProperties(properties());
        bean.setTaskExecutor(schedulerThreadPool());
        bean.setStartupDelay(0);
        return bean;
    }

    @Bean
    public Properties properties(){
        try {
            PropertiesFactoryBean properties = new PropertiesFactoryBean();
            properties.setLocation(new ClassPathResource("/quartz.properties")); //和自己配置的文件名保持一致
            properties.afterPropertiesSet();
            return properties.getObject();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
//定义的线程池 固定的写法
    @Bean
    public Executor schedulerThreadPool(){
        //创建线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置线程池的核心线程数
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        //设置最大线程数
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors());
        // 设置线程池的队列容量
        executor.setQueueCapacity(Runtime.getRuntime().availableProcessors());
        return executor;
    }
}